package com.funmi.lizip.security.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.funmi.lizip.common.base.R;
import com.funmi.lizip.entity.Personnel;
import com.funmi.lizip.entity.User;
import com.funmi.lizip.mapper.PersonnelMapper;
import com.funmi.lizip.mapper.UserMapper;
import com.funmi.lizip.security.entity.SecurityUser;
import com.funmi.lizip.security.util.JwtTokenUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private PersonnelMapper personnelMapper;
	@Autowired
	private UserMapper userMapper;

	@SneakyThrows
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		// principal就是UserDetailsService中返回的对象
		SecurityUser securityUser = (SecurityUser)authentication.getPrincipal();
		User user = securityUser.getCurrentUser();
		// 清空用户中的密码
		user.setPassword(null);

		// 根据用户名获取JWT
		String token = JwtTokenUtil.generateTokenByRSA(authentication.getName());


		// 构建返回数据
		Map<String, Object> map = new HashMap<>();
		Personnel personnel = new Personnel();

		if (!ObjectUtils.isEmpty(user)) {
			personnel.setContactTel(user.getUsername());
			personnel = personnelMapper.selectOne(new QueryWrapper<>(personnel));
			if (!ObjectUtils.isEmpty(personnel)){
				personnel.setUserId(user.getId());
				map.put("personId", personnel.getId());
				if (!ObjectUtils.isEmpty(personnel.getPhoto()) && !personnel.getPhoto().equals("")){
					map.put("photo", ("PersonnelPhoto" + "/" + personnel.getPhoto()));
				}
				user.setLoginAt(LocalDateTime.now());
				userMapper.updateById(user);
			}else {
				map.put("message","没有查询到账号对应的此巡护人员");
			}
			// 无论是否存在，返回默认头像
			map.put("photo", ("PersonnelPhoto" + "/" + "defaultPhoto.jpg"));
		}
		map.put("token", token);
		map.put("user", user);
		//这里返回JSON数据
		R success = R.success().data(map);
		response.setStatus(HttpStatus.OK.value());
		response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(success));
	}
}